package com.google.androidcamp.session4.service;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;

public class CountActivity extends Activity {
    private TextView mCounterText;
    private Handler mHandler;
    public CountTask mCountTask;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mCounterText = (TextView) findViewById(R.id.counterText);
        // 1. Count in main thread. Leads to ANR.
        //count();
        // 2. Call from a thread.
        //callCountWithinThread();
        // 3. Create and post to handler.
        mHandler = new Handler(); 
        // 4. AsyncTask.
         //mCountTask = new CountTask(this);
         //mCountTask.execute(null);
        // 5. Service.
        startAndBindService();
    }

    public void count() {
        for (int i = 1; i <= 30; ++i) {
            try {
                Thread.sleep(1000);
                final int newCount = i;
                Log.i("CountActivity", Integer.toString(newCount));
                //mCounterText.setText(Integer.toString(newCount));
                // Uncomment to post to handler.
                
                mHandler.post(new Runnable() {
                    public void run() {
                        // TODO Auto-generated method stub
                        mCounterText.setText(Integer.toString(newCount));
                    }
                });
                
            } catch (InterruptedException e) {
                Log.e("CountActivity", "Sleep interrupted.");
            }
        }
    }

    public void callCountWithinThread() {
        new Thread(new Runnable() {
            public void run() {
                count();
            }
        }).start();
    }
    
    public void updateCounter(String count) {
        mCounterText.setText(count);
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        // Uncomment to cancel the task.
        // mCountTask.cancel(true);
    }

    private void startAndBindService() {
        Intent intent = new Intent(this, CountService.class);
        startService(intent);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName name, IBinder service) {
            ((CountService.LocalBinder) service).getService().setActivity(CountActivity.this);
        }

        public void onServiceDisconnected(ComponentName name) {
        }
    };
}